package org.spbsu.apco.common.serialization;

import org.apache.commons.lang3.StringUtils;
import org.spbsu.apco.common.monitoring.event.TaskEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * User: solozobov
 * Date: 12.01.13
 */

@Component("taskEventSerializationMechanism")
public class TaskEventSerializationMechanismImpl implements SerializationMechanism {
    public byte[] serialize(final Object list) {
        Assert.notNull(list);
        Assert.isAssignable(List.class, list.getClass());
        Assert.notEmpty((List) list);

        StringBuffer sb = new StringBuffer();
        for (Object object : (List) list) {
            Assert.isAssignable(TaskEvent.class, object.getClass(), "Only task objects can serialized. Current list type: " + object.getClass());
            TaskEvent event = (TaskEvent) object;
            sb.append("{").append("E#").append(event.getEventId()).
                    append(",T#").append(event.getTaskId()).
                    append(",TP=").append(event.getTaskType()).
                    append(",F=").append(event.getOriginatorId()).
                    append(",S=").append(event.getTaskStartTime()).
                    append(",D=").append(event.getTaskDuration()).
              append("}");
        }
        return sb.toString().getBytes();
    }

    public Object deserialize(final byte[] representation) {
        List<TaskEvent> events = new ArrayList<TaskEvent>();
        for (String taskEventStr : StringUtils.split(new String(representation), "{}")) {
            if (taskEventStr.isEmpty())
                continue;

            String[] properties = StringUtils.split(taskEventStr, ",");
            Assert.isTrue(properties.length == 6, "TaskEvent representation must contain 6 fields separated by comma: " + taskEventStr);

            TaskEvent event = new TaskEvent();

            event.setEventId(getValue(properties[0], "#"));
            event.setTaskId(getValue(properties[1], "#"));

            event.setTaskType(getValue(properties[2], "="));
            event.setOriginatorId(getValue(properties[3], "="));
            event.setTaskStartTime(Long.valueOf(getValue(properties[4], "=")));
            event.setTaskDuration(Long.valueOf(getValue(properties[5], "=")));

            events.add(event);
        }
        return events;
    }

    private String getValue(String keyvalue, String separator) {
        String value = keyvalue.substring(keyvalue.indexOf(separator) + 1);
        return value.equals("null") ? null : value;
    }
}
